package com.zhongxi.guoyuan.view;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.consume.ConsumeAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.consumerYield.ConsumeData;
import com.zhongxi.guoyuan.entity.consumerYield.ConsumeDataResult;
import com.zhongxi.guoyuan.entity.consumerYield.Summary;
import com.zhongxi.guoyuan.entity.consumerYield.ToAppleyWithDraw;
import com.zhongxi.guoyuan.entity.consumerYield.TodayConsumerYield;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.view.personalCenter.WithDrawCashActivity;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * A simple {@link Fragment} subclass.
 */
public class ConsumerLoveYieldActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener2<ListView>, SwipeRefreshLayout.OnRefreshListener {

    @Bind(R.id.ivBack)
    ImageView ivBack;
    @Bind(R.id.tvTitle)
    TextView tvTitle;
    @Bind(R.id.consume_yesterday_time)
    TextView consumeYesterdayTime;
    @Bind(R.id.consume_yesterday_number)
    TextView consumeYesterdayNumber;
    @Bind(R.id.consume_no_earn)
    TextView consumeNoEarn;
    @Bind(R.id.consume_has_Earn)
    TextView consumeHasEarn;
    @Bind(R.id.consume_activity_hasearn)
    TextView consumeActivityHasearn;
    @Bind(R.id.consume_allEarn_num)
    TextView consumeAllEarnNum;
    @Bind(R.id.consume_tv_consume)
    TextView consumeTvConsume;
    @Bind(R.id.consume_withdraw_num)
    TextView consumeWithdrawNum;
    @Bind(R.id.consume_tv_withdraw)
    TextView consumeTvWithdraw;
    @Bind(R.id.consume_hold_num)
    TextView consumeHoldNum;
    @Bind(R.id.consume_tv_applywithdraw)
    TextView consumeTvApplywithdraw;
    @Bind(R.id.consume_activity_moregive)
    TextView consumeMoreGive;//消费多增红豆
    private String type;
    @Bind(R.id.swipRefreshlayout)
    SwipeRefreshLayout swipRefreshlayout;


    private PullToRefreshListView listview;


    private ConsumeAdapter adapter;
    private List<ConsumeData> data = new ArrayList<>();

    private String floatinggains = "0";
    private String fixedgains = "0";
    private String totalamount = "0";

    //已提现
    private String withdrawals = "0";

    //消费已收益
    private String consumeEarned = "";
    //待收益红豆
    private String noConsumeEarned = "";
    //总收益（消费+活动）
    private String allConsumeEarend = "";
    //现存红豆（总收益-已提现）
    private String nowHold = "";

    //赠送用户红豆数
    private String giveNum="";
    private String payGains;
    private String trim;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.fragment_consumer_love_yield);
        ButterKnife.bind(this);
        initTitle();
        tvTitle.setText("红豆宝");
        listview = (PullToRefreshListView) findViewById(R.id.yesterday_listview_record);
        listview.setMode(PullToRefreshBase.Mode.BOTH);
    }

    @Override
    protected void initData() {
        super.initData();
        adapter = new ConsumeAdapter(context);
        listview.setAdapter(adapter);
        consumeYesterdayTime.setText("昨日" + CommonTool.formatYesterday());
        getTodayYield();
    }

    private void getTodayYield() {
        type = "today";
        getServer(Url.CONSUMER_TODAY_YIELD, null, "", false, null, "get");
    }


    /**
     * 收益明细
     */
    private void getConsumeList() {
        type = "consumelist";
        String str = "&page=" + pageNum;
        getServer(Url.CONSUME_LIST, null, str, false, null, "get");
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        listview.setOnRefreshListener(this);
        listview.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
                if (data.size() == 0) {
                    swipRefreshlayout.setEnabled(true);
                } else {
                    swipRefreshlayout.setEnabled(false);
                }
            }
        });
        swipRefreshlayout.setOnRefreshListener(this);
    }

    AlertDialog dialog;

    private void toAppleyDialog() {
        dialog = new AlertDialog.Builder(this).create();
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_to_appley, null);
        final ImageView post_nopay_ivCancel = (ImageView) view.findViewById(R.id.post_nopay_ivCancel);
        TextView no_withdraw = (TextView) view.findViewById(R.id.no_withdraw);
        final EditText post_nopay_pwd = (EditText) view.findViewById(R.id.post_nopay_pwd);
        TextView post_nopay_tvSure = (TextView) view.findViewById(R.id.post_nopay_tvSure);
        dialog.setView(view);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
                if (i == KeyEvent.KEYCODE_BACK && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    return true;
                }
                return false;
            }
        });

        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.show();

        post_nopay_ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        if (nowHold != null) {
            no_withdraw.setText("您当前拥有" + DataUtil.formatDataSixPoint(nowHold) + "红豆");
        } else {
            no_withdraw.setText("您当前拥有"+ getString(R.string.sixZero,"红豆"));
        }

        post_nopay_tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                trim = post_nopay_pwd.getText().toString().trim();
                if (TextUtils.isEmpty(trim)) {
                    showShortToast("请输入提现金额" +
                            "");
                } else if (!CommonTool.isNumeric(trim)) {
                    showShortToast("请输入正确的数字");
                    //测试需要修改为5.00
                } else if (!CommonTool.sub(nowHold, "500.00")) {
                    showShortToast("抱歉,您的未提现余额不足以提现!");
                    //测试需要修改为5.00
                } else if (!CommonTool.sub(trim, "500.00")) {
                    Toast.makeText(context, "请输入大于或等于500的提现金额", Toast.LENGTH_LONG).show();

                } else if (CommonTool.sub2(trim, nowHold)) {
                    showShortToast("您输入的数量超出了您的未提现金额");
                } else {
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("amount", MyApplication.getInstance().descsc(trim));
                    type = "witchdraw";
                    getServer(Url.USER_TOAPPLEY_WITHDRAW, map, "", false, null, "post");
                    dialog.dismiss();
                }
            }
        });


    }

    @Override
    protected void processSuccessResult(String response) throws JSONException {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        swipRefreshlayout.setRefreshing(false);
        if ("today".equals(type)) {
            TodayConsumerYield todayConsumerYield = gson.fromJson(response, TodayConsumerYield.class);
            MyApplication.getInstance().setSpValue(todayConsumerYield.getSafeobj());

            if (todayConsumerYield.getUserSummary() != null && !"".equals(todayConsumerYield.getUserSummary())) {
                Summary summary = todayConsumerYield.getUserSummary();
                if (summary.getTotalamount() != null && !"".equals(summary.getTotalamount())) {
                    totalamount = summary.getTotalamount();
                } else {
                    totalamount = "0";
                }
                if (summary.getFloatinggains() != null && !"".equals(summary.getFloatinggains())) {
                    floatinggains = summary.getFloatinggains();
                } else {
                    floatinggains = "0";
                }
                if (summary.getFixedgains() != null && !"".equals(summary.getFixedgains())) {
                    fixedgains = summary.getFixedgains();
                } else {
                    fixedgains = "0";
                }
                if (summary.getWithdrawals() != null && !"".equals(summary.getWithdrawals())) {
                    withdrawals = summary.getWithdrawals();
                } else {
                    withdrawals = "0";
                }

                if (null != summary.getPaygains() && !"".equals(summary.getPaygains())) {
                    payGains = summary.getPaygains();
                } else {
                    payGains = "0";
                }

                if(null!=summary.getGivegains()&&!"".equals(summary.getGivegains())){
                    giveNum=summary.getGivegains();
                }else{
                    giveNum="0";
                }

            }
            //消费已收益
            consumeEarned = DataUtil.add(floatinggains, fixedgains);
            //待收益红豆
            noConsumeEarned = DataUtil.subtract(totalamount, consumeEarned);
            //总已收益红豆
            allConsumeEarend = DataUtil.add(consumeEarned, todayConsumerYield.getActivityGains());
            allConsumeEarend = DataUtil.add(allConsumeEarend,todayConsumerYield.getFivepercent());//加%5
            allConsumeEarend = DataUtil.add(allConsumeEarend,giveNum);//加系统赠送红豆数
            //现存红豆
            nowHold = DataUtil.subtract(allConsumeEarend, withdrawals);
            nowHold = DataUtil.subtract(nowHold, payGains);

            initInfo(todayConsumerYield);

            getConsumeList();

        } else if ("witchdraw".equals(type)) {
            ToAppleyWithDraw toAppleyWithDraw = gson.fromJson(response, ToAppleyWithDraw.class);
            MyApplication.getInstance().setSpValue(toAppleyWithDraw.getSafeobj());
            showShortToast("申请成功,已进入受理状态");
            getTodayYield();
        } else if ("consumelist".equals(type)) {

            //收益明细
            ConsumeDataResult consumeDataResult = gson.fromJson(response, ConsumeDataResult.class);
            MyApplication.getInstance().setSpValue(consumeDataResult.getSafeobj());
            if (pageNum == 1) {
                data.clear();
            }
            listview.onRefreshComplete();
            if (consumeDataResult.getData().size() > 0) {

                data.addAll(consumeDataResult.getData());
                adapter.setList(data);
            }

        }
    }

    private void initInfo(TodayConsumerYield todayConsumerYield) {

        if (null != todayConsumerYield.getPrevDayGains() && !"".equals(todayConsumerYield.getPrevDayGains())) {
            consumeYesterdayNumber.setText(DataUtil.formatDataSixPoint(todayConsumerYield.getPrevDayGains()) + "个");
        } else {
            consumeYesterdayNumber.setText(getString(R.string.sixZero,"个"));
        }
        if(null!=todayConsumerYield.getFivepercent()&&!"".equals(todayConsumerYield.getFivepercent())){
            consumeMoreGive.setText(DataUtil.formatDataSixPoint(todayConsumerYield.getFivepercent())+"个");
        }else{
            consumeMoreGive.setText(getString(R.string.sixZero,"个"));
        }

        consumeNoEarn.setText(DataUtil.formatDataSixPoint(noConsumeEarned) + "个");
        consumeHasEarn.setText(DataUtil.formatDataSixPoint(consumeEarned) + "个");
        if (null != todayConsumerYield.getActivityGains() && !"".equals(todayConsumerYield.getActivityGains())) {
            consumeActivityHasearn.setText(DataUtil.formatDataSixPoint(todayConsumerYield.getActivityGains()) + "个");
        } else {
            consumeActivityHasearn.setText(getString(R.string.sixZero,"个"));
        }
        consumeAllEarnNum.setText("总已收益红豆：" + DataUtil.formatDataSixPoint(allConsumeEarend) + "个");
        consumeWithdrawNum.setText("已经提现红豆：" + DataUtil.formatDataSixPoint(withdrawals) + "个");
        consumeHoldNum.setText("当前拥有红豆：" + DataUtil.formatDataSixPoint(nowHold) + "个");
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse result = gson.fromJson(response, BaseResponse.class);
        MyApplication.getInstance().setSpValue(result.getSafeobj());
        if (result.getCode() == 1000) {

            if(null!=trim&&!"".equals(trim)){
                if (Integer.parseInt(trim)>500&&Integer.parseInt(trim)%100!=0){
                    showShortToast("请输入大于500且是100的整数倍的值");
                }
            }
        }else
        if (result.getCode() == 1001) {
            showShortToast("用户未登录");
        } else if (result.getCode() == 1106) {
            showShortToast("用户消费分红不足");
        } else if (result.getCode() == 1666) {
            showShortToast("服务暂不可用， 请稍后重试");
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum = 1;
        getConsumeList();

    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum++;
        getConsumeList();
    }

    @Override
    protected void onDestroy() {
        ButterKnife.unbind(this);
        super.onDestroy();
    }

    @OnClick({R.id.ivBack, R.id.consume_tv_consume, R.id.consume_tv_withdraw, R.id.consume_tv_applywithdraw})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.consume_tv_consume:
//                豆豆说明
                Intent intent = new Intent(context, HtmlActivity.class);
                intent.putExtra("type", "doudouRule");
                startActivity(intent);
                break;
            case R.id.consume_tv_withdraw:
                startAct(WithDrawCashActivity.class);
                break;
            case R.id.consume_tv_applywithdraw:
                toAppleyDialog();
                break;
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        startAct(MainHomeActivity.class);
    }

    @Override
    public void onRefresh() {
        getTodayYield();
    }
}
